<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Forum extends MY_Controller {

	function index() {
		$this->load->helper('array');
				
		$data = $this->getData('forum');

		$sql = "SELECT id, subject FROM ".$this->tblf." WHERE parent_id IS NULL";
		$query = $this->db->query($sql);

		$posts = array();
		foreach ($query->result() as $result) {
			
			$sql = "SELECT tblf.posted, tblu.username as author FROM ".$this->tblf." AS tblf, ".$this->tblu." AS tblu"
					." WHERE (tblf.parent_id = ? OR tblf.id = ?)"
					." AND tblf.user_id = tblu.id ORDER BY tblf.posted DESC LIMIT 1";

			$query = $this->db->query($sql, array($result->id,$result->id));
			if ($query->result() != null) {
				$res = $query->result();
				$result->author = $res[0]->author;
				$result->posted = $res[0]->posted;
			}

			$posts[] = $result;
		}
		
				
		$d0['posts'] = $this->sortPosts($posts);

		
		
		// notTipped
		$sql = "SELECT id FROM ".$this->tblm." as tblmatches"
				." WHERE tblmatches.deadline > now()"
				." ORDER BY tblmatches.deadline ASC, tblmatches.id ASC LIMIT 1";
		
		$query = $this->db->query($sql);
		$res = $query->result();
		$match_id = $res[0]->id;

		$sql = "SELECT tblu.name AS name"
				." FROM ".$this->tblu." as tblu"
				." LEFT JOIN ".$this->tblt." AS tblt" 
				." ON ( tblu.id = tblt.user_id AND tblt.match_id = ?)"
				." WHERE tblt.tipp_id IS NULL ORDER BY name";
 		$query = $this->db->query($sql, array($match_id));
 		$notTippedUser = array();
 		foreach($query->result() as $user) {
 			$notTippedUser[] = $user->name; 		
 		} 	
		$d0['notTippedUser'] = $notTippedUser;
		
		
		
		
		// getQoutes
		$sql = "SELECT val FROM ".$this->tblc." WHERE name LIKE ?";
		$query = $this->db->query($sql, array("quotes-photo"));
		$res = $query->result();
		if (count($res) > 0) {
			$d0["quotephoto"] = json_decode($res[0]->val);
		}
		
		
		// get form data
		$d1 = array(
			'error' => $this->session->flashdata('error'),		
			'subject' => $this->session->flashdata('subject'),
			'message' => $this->session->flashdata('message')
		);
		
		$data["content"] = $this->load->view('forum-overview', $d0, true);
		$data["content"] .= $this->load->view('forum-form', $d1, true);
		$this->load->view('layout', $data);
		
	}
	
	function entry($id) {
		$this->load->helper('bbcode');
    	$data = $this->getData('forum');
    	
		$sql = "SELECT tblf.subject, tblf.message, tblf.posted as posted, tblu.username as author FROM ".$this->tblf." AS tblf, ".$this->tblu." AS tblu"
				." WHERE (tblf.parent_id = ? OR tblf.id = ?)"
				." AND tblf.user_id = tblu.id ORDER BY tblf.posted";
		$query = $this->db->query($sql, array($id,$id));
		
		$d0['posts'] = $query->result();
		
		
		// get form data
		$d1 = array(
			'parent' => $id,
			'error' => $this->session->flashdata('error'),		
			'subject' => $this->session->flashdata('subject'),
			'message' => $this->session->flashdata('message')
		);
		

		$data["content"] = $this->load->view('forum-entries', $d0, true);
		$data["content"] .= $this->load->view('forum-form', $d1, true);
		$this->load->view('layout', $data);
	}
	
	
	function insert() {
		$this->load->library('form_validation');
		
		$parent = $this->input->post('parent');

		
		$this->form_validation->set_rules('subject', 'subject', 'trim|required');
		$this->form_validation->set_rules('message', 'message', 'trim|required');

		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
			
		//echo "this->form_validation->run() -->".$this->form_validation->run();
		if($this->form_validation->run() !== FALSE) {
			$end = "";
			$this->insertEntry(
				$this->input->post('subject'),
				$this->input->post('message'),
				$parent);
		
			if (strlen($parent) > 0)
				$end = "/entry/".$parent."#lastpost";
		}
		else {
			$end = "#end";
			$data = array(
				"parent"  => $parent,
				"error"   => $this->form_validation->error_string(),
				"subject" => $this->input->post('subject'),
				"message" => $this->input->post('message')
			);
			$this->session->set_flashdata($data);
		}

		redirect('forum'.$end);
	}

	private function insertEntry($subject, $message, $parent = '') {
		
		$point = date("Y-m-d H:i:s");
		$message = strip_tags($message);
		$subject = strip_tags($subject);
		
		if (strlen($parent) > 0) {
			$sql  = "INSERT INTO ".$this->tblf."(user_id, subject, message, posted, parent_id) VALUES(?, ?, ?, ?, ?)";
			$attr = array($this->user_id, $subject, $message, $point, $parent);
			$query = $this->db->query($sql, $attr);
		}
		else {
			$sql  = "INSERT INTO ".$this->tblf."(user_id, subject, message, posted, parent_id) VALUES(?, ?, ?, ?, NULL)";
			$attr = array($this->user_id, $subject, $message, $point);
			$query = $this->db->query($sql, $attr);
		}
	}


	private function sortPosts($posts) {
		function cmp($a, $b) {
	    	$pa = $a->posted;
	    	$pb = $b->posted;
 			if ($pa == $pb) {
            	return 0;
        	}
        	return ($pa < $pb) ? +1 : -1;
        }
		uasort($posts, "cmp");
		return $posts;
	}

}
?>
